<!--
 * @Descripttion: 
 * @version: 
 * @Author: weni09
 * @Date: 2021-05-07 13:48:28
 * @LastEditors: weni09
 * @LastEditTime: 2021-06-11 16:35:25
 * @FilePath: \icoder-frontend\blog\src\components\Comment.vue
-->

<template>
<div class="comment" >
  <el-form :model="commentForm" status-icon :rules="rules" ref="commentForm" label-width="60px" class="commentForm"  id="editor-block">
 		<el-form-item label="" label-width="0px" prop="content_md" class="comment-content">
      <mavonEditor ref="editor"
      class="md"
      placeholder="请使用Markdown语法评论"
      :toolbars="toolbars"></mavonEditor>
 		</el-form-item>
        <div class="comment-submit-parent">
         <el-form-item label="昵称" prop="nickname" class="comment-submit-prop">
 		  <el-input type="any" v-model="commentForm.nickname" :disabled="getAuthUser"></el-input>
 		</el-form-item>
 		<el-form-item
 		  prop="email"
 		  label="邮箱"
           class="comment-submit-prop">
 		  <el-input v-model="commentForm.email" :disabled="getAuthUser"></el-input>
 		</el-form-item>
 		<el-form-item class="comment-submit-prop btn" label="" label-width="30px">
 		  <el-button class="submit-comment-btn" 
       :type="submitBtnType" 
       @click="submitForm('commentForm')" 
       size="medium"
       :disabled="disabled"
       :loading="loading"
       >{{submitBtnText}}</el-button>
 		</el-form-item>
      <!-- <p class="reply-flag" v-show="replyObj.replyIndex" :reply-index="replyObj.replyIndex" :replay-name="replyObj.replyName"></p> -->
      <el-tag
        class="reply-flag" 
        v-show="replyObj.replyIndex" 
        :reply-index="replyObj.replyIndex"
        closable
        :disable-transitions="false"
        @close="handleClose()">
        回复 @{{ replyObj.replyName }} [{{ replyObj.replyDesc }}]
  </el-tag>
  </div>
	</el-form>
  <div class="comment-view">
    <div class="comment-view-pub comment-header"><strong title="人数根据邮箱统计">{{ comUserCnt }} 人参与 | {{ comCnt }} 条评论</strong></div>
    <p v-if="comCnt == 0">暂无评论，欢迎留言！</p>
    <ul style="padding-left:0" v-else>
      <template v-for="(item,index) in comments">
      <li :class="'comment-parent parent_'+item.id"
      :key="index"
      > 
        <p class="reply-span"
          :class="{red:changeRed == item.id}"
          @click="clickReply(index,item.id,item.nickname,item.id)">回复</p>
        <div class="comment-avatar">
        <el-avatar class="comment-avatar-el" :size="30" sharp="circle" :src="avatar"></el-avatar>
        </div>
        <div class="comment-title">
          <p id="row-1"><strong>{{ item.nickname }}</strong>
          <span class="floor-master">{{item.email == item.author_name?'[博主]':'[楼主]'}}</span>
          </p>
          <p id="row-2">{{ index + 1 }} 楼 - {{item.create_date}}</p>
        </div>
      </li>
       <div :key="'b'+index" class="comment-body" :id="'comment-'+item.id">
            <p class="text" v-html="item.content"></p>
      </div>
      <ul :key="'ChildAll'+index" class="comment-child-ul">
      <template v-for="(itemChild,index) in item.children">
        <li :class="'comment-child child_'+itemChild.id" :key="'Child' + index" v-if="itemChild">
        <p class="reply-span"
          :class="{red:changeRed == itemChild.id}"
          @click="clickReply(index,itemChild.id,itemChild.nickname,itemChild.root_id)">回复</p>
        <div class="comment-avatar">
        <el-avatar class="comment-avatar-el" :size="30" sharp="circle" :src="avatar"></el-avatar>
        </div>
        <div class="comment-title">
          <p id="row-1"><strong>{{ itemChild.nickname }}</strong>
          <span class="floor-master">{{item.email == item.author_name?'[博主]':'[层主]'}}</span>
          <span class="iconfont icon-huifu"></span>
          <span class="comment-parent-name" @click="anchorJump('#comment-'+itemChild.parent_id,'center')">
            @{{ getParentName(itemChild.parent_id,itemChild.root_id) }}
          </span>
          </p>
          <p id="row-2">{{ index + 1 }} 层 - {{itemChild.create_date}}</p>
        </div>
        </li>
         <div :key="'ChildB'+index" class="comment-body" v-if="itemChild" :id="'comment-'+itemChild.id">
            <p class="text" v-html="itemChild.content"></p>
      </div>
      </template>
      </ul>
    </template>
    </ul>
  </div>
</div>
</template>

<script>
// import wangeditor from 'components/WangEditor.vue';
import mavonEditor from 'components/MavonEditor';
import { addComment,fetchComment } from 'api';
import { formatTime } from '@/utils/';
export default {

   components:{
			// wangeditor,
      mavonEditor,
	},
    data(){
        //评论内容校验
        var checkHtml=(rule, value, callback) => {
        // var value = value.replace(/(^\s*)|(\s*$)/g, "")
        var value = value.trim()
        if (!value) {
          return callback(new Error('请输入评论内容'));
        }
        callback();
        };
        return {
            editorHeight:260,
            commentForm: {
                article_id: this.$route.params.id,
                nickname: '',
                email:'',
                content:'',
                content_md:'',
                parent_id:0,
                root_id:0,
            },
            rules: {
                nickname: [{ required: true,min:1,max:20,message: '长度至少1个字符，最多20个字符', trigger: ['blur','change']}],
                email: [{required: true,message: '请输入邮箱地址', trigger: 'blur' },
                { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
                content_md:[{required: true,validator: checkHtml,trigger: ['blur'] }],
            },
            submitBtnType:"primary",
            submitBtnText:"提交评论",
            disabled: false,
            loading:false,
            excludeMenus:['video','image'],
            comments: Array,
            comUserCnt: Number,
            comCnt: Number,
            avatar: "http://weni09.gitee.io/picbed/avatar/2.png",
            replyColor:"",
            changeRed: Number,
            replyObj:Object,
            toolbars:{
            bold: true, // 粗体
            italic: true, // 斜体
            header: true, // 标题
            underline: true, // 下划线
            strikethrough: true, // 中划线
            mark: true, // 标记
            superscript: true, // 上角标
            subscript: true, // 下角标
            quote: true, // 引用
            ol: true, // 有序列表
            ul: true, // 无序列表
            link: true, // 链接
            code: true, // code
            fullscreen: true, // 全屏编辑
            help: true, // 帮助
            trash: true, // 清空
            alignleft: true, // 左对齐
            aligncenter: true, // 居中
            alignright: true, // 右对齐
            preview: true // 预览
            },

        };

    },
    computed:{
      getAuthUser:function(){
        if (this.$store.getters.auth.user){
          this.commentForm.email = this.$store.getters.auth.user.username
          this.commentForm.nickname = this.$store.getters.auth.user.nickname
          return true
        }
        else{
          this.commentForm.email =""
          this.commentForm.nickname = ""
          return false
        }
      },
      

    },
    methods:{
        //初始化提交按钮状态
        initSubmitBtn:function(text){
            this.submitBtnType = "primary"
            this.submitBtnText = text
            this.disabled = false
            this.loading = false
        },
        successSubmit:function(){
            this.submitBtnType = "success";
            this.submitBtnText = "提交成功！";
            this.disabled = true;
            this.loading = false;
            setTimeout(()=>{
                this.initSubmitBtn("提交评论");
            },1500)
        },
        submitting:function(){
            this.submitBtnType = "info"
            this.submitBtnText = "提交中..."
            this.disabled = true
            this.loading = true;
        },
        failedSubmit:function(){
            this.submitBtnType = "danger"
            this.submitBtnText = "提交失败！"
            this.disabled = true
            this.loading = false;
            setTimeout(()=>{
                this.initSubmitBtn("重新提交");
            },2000)
        },

        //提交表单
        submitForm(formName) {
            if(this.replyObj.replyId){
               this.commentForm.parent_id = this.replyObj.replyId
               this.commentForm.root_id = this.replyObj.rootId
              //  console.log(2,this.commentForm.root_id)
            }
            else{this.commentForm.parent_id = 0;
                 this.commentForm.root_id = 0;
            };
            this.$refs[formName].model.content_md = this.$refs.editor.content
            this.$refs[formName].model.content = this.$refs.editor.html
            this.$refs[formName].validate((valid) => {
              if (valid) {
              this.submitting(); //提交中按钮状态
              // console.log(this.$refs[formName].model)
              addComment(this.$refs[formName].model).then(res => {
              this.resetForm(formName); //提交后重置
              if (res.code == "success"){
                this.successSubmit();
                //提交成功，查询评论
                this.getComments();
                //如果是回复
                if (this.commentForm.parent_id!=0){
                  //提交成功后关闭回复标签,还原到未回复状态
                  this.handleClose();
                }
              }
            	}).catch(err => {
                  this.failedSubmit();
                	console.log(err)
            	});
              
              } else {
                return false;
              }
            });
        },
        //重置表单
        resetForm(formName) {
          this.$refs[formName].resetFields();
          this.$refs.editor.content="";
          this.$refs.editor.html="";
        },
        
        //查询评论
        getComments(){
          const params = {
					  id:this.$route.params.id
				  };
            fetchComment(params).then(res=>{

                this.comUserCnt = res.data.comment_usercnt;
                this.comCnt = res.total;
                const temp = res.data.comments;
                for (let i=0;i<temp.length;i++){
                  if(temp[i]['create_date']){
                    temp[i]['create_date']=formatTime(temp[i]['create_date'],'{Y}/{m}/{d} {h}:{i}')
                  };
                  // console.log(temp[i])
                  if(temp[i]['children']){
                    // console.log(temp[i]['children'])
                      for (let j=0;j<temp[i]['children'].length;j++){
                        temp[i]['children'][j]['create_date']=formatTime(temp[i]['children'][j]['create_date'],'{Y}/{m}/{d} {h}:{i}')
                      }
                  }
                    
                 } ;
                this.comments = temp
       
            }).catch(err => {
              console.log(err)
            })
        },

      //计算楼层号
      getFloor:function(rootId,childId){
        const temp = this.comments
        var result = ""
        var chilrenTemp=""
          for (let i in temp){
            if (temp[i]['id']==rootId){
              result = parseInt(i) + 1 + "楼"
              if (childId){
              var chilrenTemp = temp[i]['children']
              }
            }
          };
          if(chilrenTemp){
              for (let i in chilrenTemp){
                if (chilrenTemp[i]['id']==childId){
                let resultChild = parseInt(i) + 1 + "层"
                result += resultChild
                }
              }
          }
          return result
      },
      //点击回复
      clickReply(index,id,name,rootId){
        // this.$el.querySelector('#editor-block').scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
        this.anchorJump('#editor-block','center')
        this.changeRed = id
        // console.log(1,rootId)
        const replyDesc=this.getFloor(rootId,id)
        this.replyObj = {"replyIndex":index+1,"replyId": id,"replyName":name,"rootId":rootId,"replyDesc":replyDesc}
        this.initSubmitBtn("提交回复");//点击回复,改变按钮文本
        // console.log(this.replyObj)
      },
      //关闭回复提示
      handleClose(){
        //回复对象置空
        this.replyObj = {};
        //回复颜色还原
        this.changeRed = 0;
      },
      //获取回复对象(父级)名
      getParentName:function(parentId,rootId){
        const temp = this.comments;
        for (let i in temp){
          if (temp[i].id == parentId){
            this.getFloor(rootId,temp[i].id)
            return temp[i].nickname + " [" + this.getFloor(rootId,temp[i].id) + "]"
          }
          if(temp[i].id == rootId){
            var tempc = temp[i]['children']
          }
        };
        
        // console.log(tempc)
        
        if (!tempc){return ""}
        for (let j in tempc){
            if(tempc[j].id == parentId){
              return tempc[j].nickname + " [" + this.getFloor(rootId,tempc[j].id) + "]"
            }

        };
      },
      //锚点跳转
      anchorJump(nodeId,position){
          // console.log(nodeId)
          this.$el.querySelector(nodeId).scrollIntoView({behavior: "smooth", block: position, inline: "nearest"});
      },

      //初始化
        initData(){
          this.getComments()
        },


    },

    mounted(){
      
    },
    created(){
      this.initData();
    }

}
</script>

<style lang="scss" scoped>
@import '@/styles/Comment.scss';
</style>